package com.meida.module.bus.provider.handler;

import com.meida.common.mybatis.entity.EntityMap;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.provider.service.BusDeptService;
import com.meida.module.bus.provider.service.BusMajorService;
import com.meida.module.bus.provider.service.BusProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Component("materialPlan200PageListHandler")
public class Materialplan200PageListHandler implements PageInterceptor {
    @Autowired
    private BusDeptService busDeptService;
    @Autowired
    private BusProjectService busProjectService;
    @Autowired
    private BusMajorService busMajorService;

    @Override
    public void prepare(CriteriaQuery cq, PageParams pageParams, EntityMap params) {
        EntityMap requestMap = cq.getRequestMap();
////        cq.addSelect(BusProject.class, "projectName", "projectCode");
//        cq.eq("bmplan.projectId", requestMap.get("projectId"));
//        //项目代码
//        cq.like(BusProject.class, "projectCode", requestMap.get("projectCode"));
//        //项目名称
//        cq.like(BusProject.class, "projectName", requestMap.get("projectName"));
//        cq.createJoin(BusProject.class).setJoinField("projectId").setMainField("projectId");
        Long userId = OpenHelper.getUserId();
        boolean a = false;
        boolean b = false;
        List<String> userProjectIds = busProjectService.getUserProjectIds(userId);
        if (userProjectIds.size() > 0) {
            a = true;
            cq.in("bmep.projectId", userProjectIds);
        } else {
            List<String> userDeptList = busDeptService.getUserDepts(userId);
            if (userDeptList.size() > 0) {
                a = true;
                if (!userDeptList.contains("M00")) {
                    cq.apply("replace(project.deptProjectCode,',','|') regexp {0}", StringUtils.join(userDeptList, "|"));
                }
            }
        }
        List<String> userMajorList = busMajorService.getUserMajors(userId);
        if (userMajorList.size() > 0) {
            b = true;
            if (!userMajorList.contains("P99")) {
                cq.in("bmep.majorCode", userMajorList);
            }
        }

        if (a & b) {
            requestMap.put("isSet", true);
        } else {
            requestMap.put("isSet", false);
        }
        cq.setRequestMap(requestMap);
    }

    @Override
    public void complete(CriteriaQuery cq, List result, EntityMap extra) {
        EntityMap requestMap = cq.getRequestMap();
        Boolean isSet = requestMap.getBoolean("isSet");
        if (!isSet) {
            result.clear();
        }
    }
}
